import {getAbsoluteUrl, getFileExt, getMinetype} from '../utils/dom'

export default initMSE

function initMSE () {
  let activeItem
  for (let i = 0; i < this._config.playlist.length; i++) {
    const item = this._config.playlist[i]
    if (item.active) {
      activeItem = item
      break
    }
  }

  let activeSource
  for (let i = 0; i < activeItem.sources.length; i++) {
    const sour = activeItem.sources[i]
    if (sour.active) {
      activeSource = sour
    }
  }

  const file = activeSource.file
  const absoluteFile = getAbsoluteUrl(file)
  const fileExt = getFileExt(absoluteFile)
  const mineType = getMinetype(fileExt)
  const type = activeSource.type || fileExt
  const isLive = activeItem.isLive
  const image = activeItem.image

  if (this._status.plugin) {
    this._status.plugin.remove()
  }

  this.dom.video.setAttribute('poster', image || '')
  this.dom.video.setAttribute('src', file)

  const canNativePlay = this.dom.video.canPlayType(mineType)
  if (canNativePlay) {
    this._status.plugin = null
    return
  }
  const plugins = this.getPlugins()
  for (let name in plugins) {
    const Plugin = plugins[name]['plugin']
    if (Plugin.canPlayType(mineType)) {
      this._status.plugin = new Plugin(this)
      break
    }
  }
  this._status.plugin.setup({
    file,
    isLive,
    type
  })
}
